package com.csdj.article.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

public class MessageLangUtil {

    /**
     * 存放多语言资源
     */
    private static Map<Locale, ResourceBundle> bundles = new HashMap<>();

    /**
     * 从语言包中获取code对应的信息
     * @param code
     * @param lang
     * @return
     */
    public static String getMsg(int code, Locale lang){
        ResourceBundle resourceBundle = bundles.get(lang);
        if(resourceBundle == null){
            resourceBundle = ResourceBundle.getBundle("message", lang);
            bundles.put(lang,resourceBundle);
        }
        return resourceBundle.getString(String.valueOf(code));
    }

    public static String getMsg(int code){
        Locale lang = getLang();
        if(lang == null){
            lang = Locale.CHINA;
        }
        return getMsg(code,lang);
    }

    public static  Locale getLang(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(requestAttributes == null)return Locale.CHINA;
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        String header = request.getHeader("Accept-Language");
        if(StringUtils.hasText(header)){
            String lang = header.split(",")[0];
            Locale locale = Locale.forLanguageTag(lang);
            return locale;
        }
        return null;
    }
}
